The template and templateUrl Properties

Course- AngularJS >

The easiest way to create your own directives is as shown in the example above. Your directive is intended to generate HTML, and you put that HTML inside the template attribute of the directive definition object. Here is the directive definition repeated from earlier, with the template string marked in bold:

myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.template = "My first directive: {{textToInsert}}";

    return directive;
});

In case that HTML template grows big, it is gets hard to write and maintain the HTML inside a JavaScript string. You can then put the HTML into its own file and have AngularJS load it from that file. You do so by putting the URL of the HTML template file into the templateUrl property of the directive definition object. Here is an example:

myapp = angular.module("myapp", []);

myapp.directive('div', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.templateUrl = "/myapp/html-templates/div-template.html";

    return directive;
});

AngularJS will now load the HTML template from the URL set in the templateUrl property.

Using the separate HTML template file and the templateUrl property is especially useful when you create more specialized directives, like a directives showing user info. Here is an example:

myapp = angular.module("myapp", []);

myapp.directive('userinfo', function() {
    var directive = {};

    directive.restrict = 'E'; /* restrict this directive to elements */
    directive.templateUrl = "/myapp/html-templates/userinfo-template.html";

    return directive;
});

This example creates a directive that is activated whenever AngularJS finds a <userinfo> element. AngularJS loads the HTML template found at /myapp/html-templates/userinfo-template.html, and interprets that as if it had been located inside the parent HTML file from the beginning.